<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableExpose } from '@/components/Table'
import { DmList, updDeptInfo ,del ,updDeptStatus} from '@/api/table'
import { TableData } from '@/api/table/types'
import { ref, h, reactive, unref , onMounted} from 'vue'
import { ElTag, ElMessage , ElButton,ElMessageBox,ElSwitch } from 'element-plus'
import { useTable } from '@/views/Order/OrderList'
import { Pagination, TableColumn, TableSlotDefault } from '@/types/table'
import { Form } from '@/components/Form'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import {FormSchema, FormSetPropsType} from "@/types/form";

//隐藏的弹窗
const dialogVisible = ref(false);

//查询组件
const schema = reactive<FormSchema[]>([
  {
    field: 'deptName',
    label: '部门：',
    component: 'Input'
  },
  {
    field: 'trueName',
    label: '管理员：',
    component: 'Input'
  },
  {
    field: 'createDate',
    label: '创建日期：',
    component: 'DatePicker',
    componentProps: {
      type: 'date',
      format: 'YYYY/MM/DD',
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'deptStatus',
    label: '状态：',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '启用',
          value: '1'
        },
        {
          label: '未启用',
          value: '2'
        }
      ],
      onChange: (value: string) => {
        console.log(value)
      }
    }
  }
]);
//折叠组件范围

const { t } = useI18n();

var JudgingCondition = true;
//表头
const columns = reactive<TableColumn[]>([
  {
    field: '',
    label: '序号',
    type: 'index'
  },
  {
    field: 'deptName',
    label: '部门名称'
  },
  {
    field: 'deptDescirbe',
    label: '部门描述'
  },
  {
    field: 'trueName',
    label: '创建人'
  },
  {
    field: 'updateDate',
    label: '创建时间',
    formatter: (_: Recordable, __: TableColumn, cellValue: number) => {
      return h(
              () =>{
                var date1 = new Date(cellValue).toJSON();
                var date = new Date(+new Date(date1)+8*3600*1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'');
                date.substr(0,10); //接取2020-04-02
                return date;
              }
      )
    }
  },
  {
    field: 'deptStatus',
    label: '状态',
    formatter: (_: Recordable, __: TableColumn, cellValue: number) => {
      return h(
              ElTag,
              {
                type: cellValue === 1 ? 'success' : cellValue === 2 ? 'danger' : 'warning'
              },
              () =>
                      cellValue == 1
                              ? "启用"
                              : cellValue == 2
                              ? "未启用"
                              : "状态有误"
      )
    }
  },
  {
    field: 'action',
    label: '操作'
  }
]);

const { register, tableObject, methods } = useTable<TableData>({
  getListApi: DmList,
  response: {
    list: 'list',
    total: 'total'
  },
  props: {
    columns
  },
  defaultParams: {

  }
});

const { getList ,setSearchParams } = methods;

getList();

const tableRef = ref<TableExpose>();
var lor;
var RowValue = null;
//查看按钮执行的函数
const actionFn = (data: TableSlotDefault) => {
  RowValue = data.row
  console.log(RowValue)

  lor = reactive<Form[]>([
    {
      field: 'updateId',
      component: 'Input',
      value: 1,
      hidden:true
    },
    {
      field: 'deptId',
      label: '部门ID',
      component: 'Input',
      value: RowValue.deptId,
      hidden:true
    },
    {
      field: 'deptName',
      label: '部门名称',
      component: 'Input',
      value: RowValue.deptName
    },
    {
      field: 'field1',
      label: '创建人',
      component: 'Input',
      value:RowValue.trueName
    },
    {
      field: 'field2',
      label: '创建时间',
      component: 'Input',
      value:RowValue.createDate
    },
    {
      field: 'deptDescirbe',
      label: '部门描述',
      component: 'Input',
      componentProps: {
        type: 'textarea',
        rows: 2
      },
      value:RowValue.deptDescirbe
    },
  ]);

};

const paginationObj = ref<Pagination>();

const showPagination = (show: boolean) => {
  if (show) {
    var fff = document.querySelector('#fff');
    fff.remove()
    paginationObj.value = {
      total: tableObject.total
    }
  } else {
    paginationObj.value = undefined
  }
};

const reserveIndex = (custom: boolean) => {
  unref(tableRef)?.setProps({
    reserveIndex: custom
  })
};

const showSelections = (show: boolean) => {
  unref(tableRef)?.setProps({
    selection: show
  })
};

const index = ref(1);

const changeTitle = () => {
  unref(tableRef)?.setColumn([
    {
      field: 'title',
      path: 'label',
      value: `${t('tableDemo.title')}${unref(index)}`
    }
  ])
  index.value++
};

const showExpandedRows = (show: boolean) => {
  unref(tableRef)?.setProps({
    expand: show
  })
};

const selectAllNone = () => {
  unref(tableRef)?.elTableRef?.toggleAllSelection()
};

function stopEnable(row) {
  console.log(row.enabled)
  updDeptStatus({"deptStatus":row.deptStatus,"deptId":row.deptId}).then((res) =>{
    if (res) {
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
    }else {
      ElMessage.error('修改失败')
    }
  });
}

//修改
const upLoad = () => {
  console.log(lor)

  updDeptInfo({"updateId":lor[0].value,"deptId":lor[1].value,"deptName":lor[2].value,"deptDescirbe":lor[5].value}).then((res) =>{
    if (res.data){
      ElMessage({
        message: '编辑成功.',
        type: 'success',
      })
    } else {
      ElMessage.error('编辑失败.')
    }
  })
}
//删除按钮
const Delete = (data: TableSlotDefault) =>{
  var id = data.row.deptId;
  del({"deptId":id}).then((res) =>{
    if (res.data){
      ElMessage({
        message: '删除成功.',
        type: 'success',
      })
    } else {
      ElMessage.error('删除失败.')
    }
  })
}
//删除询问
const Open = (data: TableSlotDefault) => {
  ElMessageBox.confirm(
          '您确定要删除此部门吗?',
          '提示',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
  )
          .then(() => {
            Delete(data)
          })
          .catch(() => {
            ElMessage({
              type: 'warning',
              message: '取消删除!',
            })
          })
}
</script>

<template>
<!-- 查询表单 -->
  <ContentWrap :title="`筛选查询`">
    <Search
            :showReset="false"
            :schema="schema"
            @search="setSearchParams"
            @reset="setSearchParams"
    />
  </ContentWrap>
<!--表格-->
  <br>
  <ContentWrap :title="`商品订单列表`" >
    <Table
      ref="tableRef"
      border="1px"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :data="tableObject.tableList.slice((tableObject.currentPage-1)*tableObject.pageSize,tableObject.currentPage*tableObject.pageSize)"
      :loading="tableObject.loading"
      :pagination="{total: tableObject.total}"
      @register="register"
    >

      <!--是否启用-->
      <template #deptStatus="{row}">
        <ElSwitch
                v-model="row.deptStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                @change="stopEnable(row)"
                :inactive-value="2">
        </ElSwitch>
      </template>

      <template #action="data">
        <ElButton type="primary" link size="small" @click="dialogVisible = !dialogVisible;actionFn(data as TableSlotDefault)">
          编辑
        </ElButton>
        <ElButton link @click="Open(data as TableSlotDefault)" type="primary" size="small">
          删除
        </ElButton>
      </template>

      <template #expand="data">
        <div class="ml-30px">
          <div>{{ t('tableDemo.title') }}：{{ data.row.title }}</div>
          <div>{{ t('tableDemo.author') }}：{{ data.row.author }}</div>
          <div>{{ t('tableDemo.displayTime') }}：{{ data.row.display_time }}</div>
        </div>
      </template>
    </Table>
  </ContentWrap>

<!--  编辑弹窗-->
  <Dialog open-delay="300" maxHeight="205px"  width="30%" v-model="dialogVisible" title="编辑">
    <Form
          :isCol="false"
          :schema="lor"/>

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" @click="dialogVisible = false;upLoad()" :loading="loading">
        编辑
      </ElButton>
      <ElButton @click="dialogVisible = false">
        取消
      </ElButton>
    </template>
  </Dialog>

</template>

